<template>
  <!--  <van-button size="small" icon="search" type="primary" @click="openSearchDialog">筛选</van-button>-->
  <E10SearchBar
    :placeholder="e10SearchPlaceholder"
    :search-able="false"
    action-text="清空"
    @on-click="openSearchDialog"
    @clear="onClear"
    @action="emit('action')"
  />
  <van-dialog
    v-model:show="_show"
    title="信息筛选"
    show-cancel-button
    teleport="body"
    :before-close="onBeforeClose"
  >
    <div style="max-height: 65vh; overflow: auto; margin-top: 1vh">
      <template
        v-for="({ displayName, property, fieldType, reference }, index) in filterPropertyList"
        :key="property"
      >
        <template v-if="fieldType === FIELD_TYPE.SELECT || fieldType === FIELD_TYPE.SELECT_MULTI_IN_ONE">
          <MultiSelect v-model="filterPropertyList[index].filterValues" :label="displayName" :dict="reference" />
        </template>
        <template v-else-if="fieldType === FIELD_TYPE.TREE || fieldType === FIELD_TYPE.TREE_MULTI_IN_ONE">
          <MultiSelect
            v-model="filterPropertyList[index].filterValues"
            :label="displayName"
            :dict="reference"
            tree
          />
        </template>
        <template v-else-if="fieldType === FIELD_TYPE.DATE">
          <DateRangePicker v-model:date-range="filterPropertyList[index].filterValues" :label="displayName" />
        </template>
        <template v-else-if="fieldType === FIELD_TYPE.DATETIME">
          <DateRangePicker
            v-model:date-range="filterPropertyList[index].filterValues"
            :label="displayName"
            type="dateTime"
          />
        </template>
        <template v-else-if="fieldType === FIELD_TYPE.NUMBER || fieldType === FIELD_TYPE.MONEY">
          <NumberSelect
            v-model:value="filterPropertyList[index].filterValues"
            :field-type="FIELD_TYPE.NUMBER"
            :label="displayName"
          />
        </template>
        <template v-else>
          <van-field
            v-model="filterPropertyList[index].filterValues[0]"
            :placeholder="`请输入${displayName}`"
            label-align="top"
          >
            <template #label>
              <div class="input-label">
                {{ displayName }}
              </div>
            </template>
          </van-field>
        </template>
      </template>
    </div>
  </van-dialog>
</template>

<script setup lang="ts">
import { showError } from '@/framework/common/notify'
import { useRouterStore } from '@/framework/store/router'
import MultiSelect from '@/framework/components/MultiSelect/index.vue'
import NumberSelect from '@/framework/components/NumberSelect/index.vue'
import { ConditionListType, FIELD_TYPE } from '@/framework/types/portal.d'
import E10SearchBar from '@/framework/components/e10/E10SearchBar/index.vue'
import DateRangePicker from '@/framework/components/DateRangePicker/index.vue'
import { getDefaultFilterType } from '@/framework/components/PortalData/DataFilter/funs'

const props = defineProps<{
  items: Array<any>
}>()

const { items } = toRefs(props)

const filterPropertyList = computed(() =>
  items.value.filter((item: any) => item.filterAble === '1' && item.show === '1')
)

const onClear = () => {
  items.value.forEach((item) => {
    item.filterValues = []
  })
  e10SearchPlaceholder.value = defaultE10SearchPlaceholder
  emit('onQueryFilter', [])
}

let _show = ref(false)
const routerStore = useRouterStore()
const defaultE10SearchPlaceholder = '请添加筛选条件'
const e10SearchPlaceholder = ref(defaultE10SearchPlaceholder)
const openSearchDialog = () => (_show.value = true)
const emit = defineEmits<{
  (e: 'action'): void
  (e: 'update:show', value: boolean): void
  (e: 'onQueryFilter', queryCondition: ConditionListType[]): void
}>()

const onBeforeClose = (action: string) => {
  if (action === 'confirm') return new Promise<boolean>((resolve) => resolve(onConfirmFilter()))
  return true
}

watch(
  () => _show.value,
  () => routerStore.blockReturn(_show.value, () => (_show.value = false)),
  { immediate: true }
)

const onConfirmFilter = () => {
  const isExistIllegalNumberItem = items.value.some(({ fieldType, filterValues, displayName }: any) => {
    if (fieldType === FIELD_TYPE.NUMBER || fieldType === FIELD_TYPE.MONEY) {
      if (filterValues.some((value: string) => !value)) {
        showError(`${displayName}数值需要填写两个边界值，请校对！`)
        return true
      }
      return false
    }
    return false
  })
  if (isExistIllegalNumberItem) return false
  const queryConditionList = items.value.filter((item: any) => {
    const { filterValues } = item
    if (typeof filterValues === 'string') return !!filterValues
    else if (Array.isArray(filterValues)) return filterValues.filter((item: any) => !!item).length
    else {
      console.error('未知类型，查询条件不予提交')
      return false
    }
  })

  const queryCondition = queryConditionList.map((item: any) => {
    const { property, filterValues, fieldType, filterStrict } = item
    let value = filterValues
    if (typeof filterValues === 'string') value = [filterValues]
    return {
      property: property as string,
      value: value as Array<any>,
      relation: +getDefaultFilterType(fieldType, filterStrict)
    } as ConditionListType
  })
  if (queryCondition.length) e10SearchPlaceholder.value = '已设置筛选条件'
  else e10SearchPlaceholder.value = defaultE10SearchPlaceholder
  emit('onQueryFilter', queryCondition)
  return true
}
</script>

<style scoped>
.input-label {
  display: flex;
  align-items: center;
}
</style>
